package net.qhzw.vip.qiyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.wxpay.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import net.qhzw.vip.qiyu.config.ApiConfig;
import net.qhzw.vip.qiyu.entity.Order;
import net.qhzw.vip.qiyu.entity.OrderItem;
import net.qhzw.vip.qiyu.entity.OrderRefunds;
import net.qhzw.vip.qiyu.enums.OrderStatus;
import net.qhzw.vip.qiyu.handler.ApiException;
import net.qhzw.vip.qiyu.mapper.OrderRefundsMapper;
import net.qhzw.vip.qiyu.param.PayParam;
import net.qhzw.vip.qiyu.service.*;
import net.qhzw.vip.qiyu.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 退款详情
 */
@Slf4j
@Service
public class OrderRefundsServiceImpl extends ServiceImpl<OrderRefundsMapper, OrderRefunds>
        implements OrderRefundsService {

    @Autowired
    private OrderRefundsMapper orderRefundsMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private ProductService productService;

    @Autowired
    private SkuService skuService;

//    @Autowired
//    private WxPayService wxMiniPayService;

    @Autowired
    private ApiConfig apiConfig;

    @Autowired
    private PayService payService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean requestRefund(OrderRefunds orderRefunds) {
        String orderNumbers = orderRefunds.getOrderNumber();
        Order order = orderService.getOrderByOrderNumber(orderNumbers);
        Integer orderStatus = order.getStatus();
        order.setStatus(11);
        orderService.updateById(order);
        if (order == null)
            throw new ApiException("订单不存在!");
        if (orderStatus > 3)
            throw new ApiException("不可退换");
        Long userId = SecurityUtils.getUserId();
        orderRefunds.setUserId(userId);
        orderRefunds.setStatus((byte) 1);
        orderRefunds.setRefundAmount(order.getActualTotal());
        return save(orderRefunds);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean doOrderRefunds(OrderRefunds orderRefund) {
        OrderRefunds orderRefunds = getOne(new LambdaQueryWrapper<OrderRefunds>()
                .eq(OrderRefunds::getOrderNumber, orderRefund.getOrderNumber()));
        if (orderRefunds == null)
            throw new ApiException("退款详情不存在, 订单号错误!");
        //回退商品
        Order order = orderService.getOrderByOrderNumber(orderRefunds.getOrderNumber());
        if (order == null)
            throw new ApiException("订单不存在, 订单号错误!");
        Long userId = SecurityUtils.getUserId();
        orderRefunds.setCreateId(userId);
        orderRefunds.setLastUpdateTime(new Date());
        //拒绝退款
        if (Objects.equals(orderRefunds.getStatus(), OrderStatus.CONFIRM.value())) {
            order.setRefundsRemark(orderRefund.getRefuseRefundReson());
            order.setStatus(2);
            orderService.updateById(order);
            orderRefunds.setStatus((byte) 4);
            return updateById(orderRefunds);
        }
        orderRefunds.setStatus((byte) 3);
        updateById(orderRefunds);
        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(orderRefunds.getOrderNumber());
        order.setOrderItems(orderItems);
        // 取消订单
        orderService.cancelOrders(Arrays.asList(order), (byte) 12);
        // 清除缓存
        for (OrderItem orderItem : orderItems) {
            productService.removeProductCacheByProdId(orderItem.getProdId());
            skuService.removeSkuCacheBySkuId(orderItem.getSkuId(), orderItem.getProdId());
        }
        log.info("【支付退款】：{}", orderRefunds.getOrderNumber(), userId);
        payService.refund(order.getUserId(), new PayParam(orderRefunds.getOrderNumber(), 1));
        return true;
    }

}
